import { setList, getList } from "./const/subApps"
import { rewriteRouter } from "./router/rewriteRouter";
import { currentApp } from "./utils"
import { setMainLifeCycle } from "./const/mainLifeCycle";
import { Custom } from './customEvent'
import { prefetch } from "./loader/prefetch";

const custom = new Custom()
custom.on('test', (data) => {
  console.log(data, 'test----');
  
})
window.custom = custom
// 实现路由拦截
rewriteRouter()

export const registerMicroApps = (appList, lifeCycle) => {  
  setList(appList)
  // lifeCycle.beforeLoad[0]()
  // setTimeout(() => {
  //   lifeCycle.mounted[0]()
  // },3000)
  setMainLifeCycle(lifeCycle)
}

// 启动微前端框架
export const start = () => {
  // 首先验证当前子应用列表是否为空
  const apps = getList()

  if (!apps.length) {
    // 子应用列表为空
    throw Error('子应用列表为空，请正确注册');
  }
  // 有子应用的内容，查找到符合当前路由的子应用
  const app = currentApp()
  // console.log(app, '有子应用的内容，查找到符合当前路由的子应用');
  if (app) {
    const { pathname, hash } = window.location
    const url = pathname + hash
    window.__CURRENT_SUB_APP__ = app.activeRule
    window.history.pushState('', '', url)
  }
  // 预加载-加载接下来的所有子应用，但是不显示
  prefetch()
}
